package com.qzh.QLanguage.ElementAnalyse;

import java.util.List;

// 语法解析器（支持函数调用嵌套）
class QParser {
    private final List<Token> tokens;
    private int pos = 0;
    private final QInterpreter interpreter;

    public QParser(List<Token> tokens) {
        this.tokens = tokens;
        this.interpreter = new QInterpreter();
    }

    public void parse() throws SyntaxException {
        while (!match(TokenType.EOF)) {
            parseStatement();
        }
    }

    private void parseStatement() {
        if (match(TokenType.KEYWORD)) {
            parsePrintStatement();
        }
        consume(TokenType.SEMICOLON, "期望分号");
    }

    private void parsePrintStatement() {
        consume(TokenType.KEYWORD, "print");
        consume(TokenType.LPAREN, "期望左括号");
        String message = consume(TokenType.STRING).value;
        consume(TokenType.RPAREN, "期望右括号");
        interpreter.executePrint(message);
    }

    private Token consume(TokenType expected, String errorMsg) {
        if (check(expected)) {
            return advance();
        }
        throw new SyntaxException(errorMsg + "，实际得到: " + peek().type, peek().line);
    }

    private Token consume(TokenType expected) {
        return consume(expected, "期望 " + expected);
    }

    private boolean match(TokenType type) {
        if (check(type)) {
            advance();
            return true;
        }
        return false;
    }

    private boolean check(TokenType type) {
        return !isAtEnd() && peek().type == type;
    }

    private Token advance() {
        if (!isAtEnd()) pos++;
        return previous();
    }

    private Token peek() {
        return tokens.get(pos);
    }

    private Token previous() {
        return tokens.get(pos - 1);
    }

    private boolean isAtEnd() {
        return peek().type == TokenType.EOF;
    }
}